#coding:utf-8

#sae flask 微信公众平台开发代码 
#1.实现发送任意信息自动回复 2015.9.29

from flask import Flask, request, make_response
import hashlib
import xml.etree.ElementTree as ET
import time

app = Flask(__name__)
app.debug = True

@app.route('/', methods=['GET', 'POST'])
def wechat_auth():
    if request.method == 'GET':
        return checkSignature(request)
    else:
        return responseMsg(request)

def checkSignature(request):
    token = 'weixin'
    signature = request.args.get('signature', '')
    timestamp = request.args.get('timestamp', '')
    nonce = request.args.get('nonce', '')
    echoStr = request.args.get('echostr', '')
    tmpStr = ''.join(sorted([token, timestamp, nonce]))
    if hashlib.sha1(tmpStr).hexdigest() == signature:
        return make_response(echoStr)

def responseMsg(request):
    rec = request.stream.read()
    xml_rec = ET.fromstring(rec)
    msgtype = xml_rec.find('MsgType').text
    toUsername = xml_rec.find('ToUserName').text
    fromUsername = xml_rec.find('FromUserName').text
    xml_rep_img = '''<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                </xml>'''
    if msgtype == "event":
        msgcontent = xml_rec.find('Event').text
        if msgcontent == "subscribe":
            msgcontent = "error_msg"
            response = make_response(xml_rep_img % (fromUsername, toUsername, str(int(time.time())), msgcontent))
            # response.content_type='application/xml'
            # return response
    elif msgtype == "text":
        content = xml_rec.find('Content').text
        response = make_response(xml_rep_img % (fromUsername, toUsername, str(int(time.time())), content))
    response.content_type='application/xml'
    return response